package com.ruoyi.project.module.location.service;

import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.project.module.purchases.domain.Purchases;
import com.ruoyi.project.module.purchases.mapper.PurchasesMapper;
import org.apache.commons.collections.list.PredicatedList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.module.location.mapper.LocationMapper;
import com.ruoyi.project.module.location.domain.Location;
import com.ruoyi.project.module.location.service.ILocationService;
import com.ruoyi.common.support.Convert;

/**
 * 货物位置 服务层实现
 *
 * @author lcx
 * @date 2018-10-08
 */
@Service
public class LocationServiceImpl implements ILocationService {
    @Autowired
    private LocationMapper locationMapper;
    @Autowired
    private PurchasesMapper purchasesMapper;

    /**
     * 查询货物位置信息
     *
     * @param locationId 货物位置ID
     * @return 货物位置信息
     */
    @Override
    public Location selectLocationById(Integer locationId) {
        return locationMapper.selectLocationById(locationId);
    }

    /**
     * 查询货物位置列表
     *
     * @param location 货物位置信息
     * @return 货物位置集合
     */
    @Override
    public List<Location> selectLocationList(Location location) {
        if (StringUtils.isEmpty(location.getLocationName())
                && StringUtils.isEmpty(location.getProductName())
                && StringUtils.isEmpty(location.getEan())
                && StringUtils.isEmpty(location.getSku())) {
            return locationMapper.selectLocationList(location);

        }
        //递归查询
        else {
            location.setLocationType("H");
            List<Location> list = locationMapper.selectLocationList(location);

            List<Location> relist = new ArrayList<>();

            for (Location location_tem : list) {
                selectPaLocation(location_tem.getLocationId(), relist);
            }
            return relist;
        }
    }

    /*递归查询父节点*/
    private void selectPaLocation(Integer locationId, List<Location> relist) {
        Location location = locationMapper.selectLocationById(locationId);
        //判断集合池中是否存在此元素
        if (checkList(location, relist)) {
            relist.add(location);
        }
        if (location.getParentId() != 0) {
            Integer ParentId = location.getParentId();
            selectPaLocation(ParentId, relist);
        }
    }

    /*递归查询子节点 子节点id */
    private void selectPaLocationSon(Integer locationId, List<Location> relist) {
        List<Location> locationList = locationMapper.selectLocationByIdAsSon(locationId);

        relist.addAll(locationList);

        if (locationList.size() != 0) {
            for (Location location :locationList){
            //用父类 的 id 去查询子类的父类id
            Integer locationIdTem = location.getLocationId();
            selectPaLocationSon(locationIdTem, relist);
            }
        }
    }

    /*判断是否重复*/
    private boolean checkList(Location location, List<Location> relist) {
        for (Location tem : relist) {
            if (location.getLocationId().equals(tem.getLocationId())) {
                return false;
            }
        }
        return true;
    }

    /**
     * 新增货物位置
     *
     * @param location 货物位置信息
     * @return 结果  useGeneratedKeys="true"、keyProperty="id"
     */
    @Override
    public List<Integer> insertLocation(Location location) {
        List<Location> relist = new ArrayList<>();
        List<Integer> reIds = new ArrayList<>();
        //插入数据返回此id 并且 递归父亲id
        locationMapper.insertLocation(location);

        selectPaLocation(location.getLocationId(), relist);

        relist.forEach((locationtem) -> reIds.add(locationtem.getLocationId()));

        return reIds;
    }

    /**
     * 修改货物位置
     *
     * @param location 货物位置信息
     * @return 结果
     */
    @Override
    public List<Integer> updateLocation(Location location) {
        //插入数据返回此id 并且 递归父亲id
        List<Location> relist = new ArrayList<>();
        List<Integer> reIds = new ArrayList<>();
        locationMapper.updateLocation(location);
        selectPaLocation(location.getLocationId(), relist);

        relist.forEach((locationtem) -> reIds.add(locationtem.getLocationId()));
        return reIds;
    }

    /**
     * 删除货物位置对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteLocationByIds(String ids) {

        int fal = 0;

        //查询当前操作对象的信息
        Location location = locationMapper.selectLocationById(Integer.valueOf(ids));
        List<Location> delList = new ArrayList<>();
        delList.add(location);
        //递归查询子类
        selectPaLocationSon(Integer.valueOf(ids),delList);

        //数量不多暂时不考虑性能 = - = 没时间
        for (Location dellocation:delList){
            locationMapper.deleteLocationById(dellocation.getLocationId());
            fal++;
        }

        return fal;
    }

    /*加载菜单树*/
    @Override
    public List<Map<String, Object>> locationTreeData() {
        List<Map<String, Object>> trees = new ArrayList<Map<String, Object>>();
        List<Location> menuList = locationMapper.selectLocationAll();
        trees = getTrees(menuList, false, null, false);
        return trees;
    }

    /*查询栅格数量*/
    @Override
    public int selectCountLocationByParentId(String locationId) {
        return locationMapper.selectCountLocationByParentId(locationId);
    }

    /*检测仓位是否重复*/
    @Override
    public String checkLocationNameUnique(Location location) {
        Long menuId = StringUtils.isNull(location.getLocationId()) ? -1L : location.getLocationId();
        Location info = locationMapper.checkLocationNameUnique(location.getLocationName());
        if (StringUtils.isNotNull(info) && info.getLocationId().longValue() != menuId.longValue()) {
            return UserConstants.MENU_NAME_NOT_UNIQUE;
        }
        return UserConstants.MENU_NAME_UNIQUE;
    }

    /* 根据类型查询货架*/
    @Override
    public List<Location> selectCountLocationByType(Location location) {
        return locationMapper.selectLocationList(location);
    }

    /*扫码上架 通过接口查询到 对应的商品 在货物位置上架一个商品*/
    @Override
    public List<String> updateLocationAsSweepCodeLocation(String[] smIds, String locationId, String state) {
        List<String> reList = new ArrayList<>();
        List<String> temList = new ArrayList<>();

        /*筛选是否有单号错误的记录*/
        for (String stid : smIds) {
            //查询是是否在货架上有此商品
            Location location = new Location();
            location.setPrintId(stid);
            location.setVisible("0");
            //扫码上架
            if ("SweepCodeLocation".equals(state)) {
                Purchases purchases = purchasesMapper.selectPurchasesBySweepCodeId(stid.trim());
                List<Location> locationList = locationMapper.selectLocationList(location);
                if (purchases == null || locationList.size() > 0) {
                    reList.add(stid);
                } else {
                    temList.add(purchases.getProductId());
                }
            }//扫码移位
            else if ("SweepCodeLocationY".equals(state)) {
                Purchases purchases = purchasesMapper.selectPurchasesBySweepCodeId(stid.trim());
                if (purchases == null) {
                    reList.add(stid);
                } else {
                    temList.add(purchases.getProductId());
                }
            }
        }
        /*如果都存在则插入*/
        if (reList.size() == 0) {
            for (String stid : smIds) {
                Purchases purchases = purchasesMapper.selectPurchasesBySweepCodeId(stid.trim());
                //插入货物位置
                Location location = new Location();
                //扫码上架
                if ("SweepCodeLocation".equals(state)) {
                    location.setLocationName(purchases.getProductName());
                    location.setParentId(Integer.valueOf(locationId));
                    location.setCompanyId(purchases.getCompanyId());
                    location.setProductId(purchases.getProductId());
                    location.setPrintId(stid);
                    location.setLocationType("H");
                    locationMapper.insertLocation(location);
                }
                //扫码移位
                else if ("SweepCodeLocationY".equals(state)) {
                    location.setPrintId(stid);
                    location.setParentId(Integer.valueOf(locationId));
                    locationMapper.updateLocationByPrintId(location);
                }
            }
        }

        return reList;
    }

    /*扫码下架*/
    @Override
    public List<String> updateLocationAsSweepCodeLocationX(String[] smIds) {
        List<String> reList = new ArrayList<>();
        /*筛选是否有单号错误的记录*/
        for (String stid : smIds) {
            //查询是是否在货架上有此商品
            Location location = new Location();
            location.setPrintId(stid);
            location.setVisible("0");
            List<Location> locationList = locationMapper.selectLocationList(location);
            if (locationList.size() == 0) {
                reList.add(stid);
            }
        }
        /*如果都存在则插入*/
        if (reList.size() == 0) {
            for (String stid : smIds) {
                locationMapper.deleteLocationByPrintId(stid);
            }
        }
        return reList;
    }

    /*通过sku查询商品位置*/
    @Override
    public Map<String,List<String>> selectLocationAsMainSKU(String[] skus) {

        Map<String,List<String>> reMap = new HashMap();

        //查询需要查询的商品父类id
        for (String sku : skus){
            List<String> reList = new ArrayList<>();

            Location location = new Location();
            location.setSku(sku);
            location.setLocationType("H");
            List<Location>locationList = locationMapper.selectLocationListAsMainsku(location);

            for (Location location_tem : locationList){
                reList.add(location_tem.getParentName());
            }
            reMap.put(sku,reList);
        }

        return reMap;
    }

    /* 批量打印 和 单个打印 货架标签编码*/
    @Override
    public List<Location> selectLocationAsPrintLabel(String ids) {

        List<Location> locationList = new ArrayList<>();
        String id[] = ids.split(",");

        //查询货架表

        for (String id_tem : id) {
            Location tem_location = locationMapper.selectLocationById(Integer.valueOf(id_tem));
            locationList.add(tem_location);
        }

        return locationList;
    }

    /*查询打印标签 通过 标签id*/
    @Override
    public List<Purchases> selectLocationListAsPringId(String ids) {
        Location location = new Location();
        List<Purchases> purchasesList = new ArrayList<>();

        location.setPrintId(ids);
        purchasesList.add(purchasesMapper.selectPurchasesBySweepCodeId(ids));

        return purchasesList;
    }

    /**
     * 对象转菜单树
     *
     * @param locationList 菜单列表
     * @param isCheck      是否需要选中
     * @param roleMenuList 角色已存在菜单列表
     * @param permsFlag    是否需要显示权限标识
     * @return
     */
    public List<Map<String, Object>> getTrees(List<Location> locationList, boolean isCheck, List<String> roleMenuList,
                                              boolean permsFlag) {
        List<Map<String, Object>> trees = new ArrayList<Map<String, Object>>();
        for (Location location : locationList) {
            Map<String, Object> deptMap = new HashMap<String, Object>();
            deptMap.put("id", location.getLocationId());
            deptMap.put("pId", location.getParentId());
            //deptMap.put("name", transMenuName(location, roleMenuList, permsFlag));
            deptMap.put("name", location.getLocationName());
            if (isCheck) {
                //deptMap.put("checked", roleMenuList.contains(location.getMenuId() + location.getPerms()));
            } else {
                deptMap.put("checked", false);
            }
            trees.add(deptMap);
        }
        return trees;
    }


}
